﻿package {
	public class Engine {
		import flash.display.*;
		import flash.events.*;
		import com.soulwire.media.MotionTracker;
		
		private var bubbles:Array;
		private var loc_mc:Box = new Box();
		private var displayer:MovieClip;
		private var motionTracker:MotionTracker
		private var currentBubble:BubbleMovieClip = null;
		private var listener:Function;
		private var flow = false;
		
		public function Engine(bubbles:Array, displayer:MovieClip, motion:MotionTracker) {
			this.bubbles = bubbles;
			this.displayer = displayer;
			this.motionTracker = motion;
			
			displayer.addChild(loc_mc);
			loc_mc.width = 100;
			loc_mc.height = 100;
			loc_mc.x = displayer.width / 2;
			loc_mc.y = displayer.height / 2;
		}
		
		public function run() {
			for(var i:int = 0; i < bubbles.length; i++) {
				var bob:BubbleMovieClip = bubbles[i];
				bob.init();
				displayer.addChild(bob);
				bob.setExplodeListener(
					function() {
						flow = true;
						cleanBox();
						for(var j:int = 0; j < bubbles.length; j++) {
							bubbles[j].destroy();
						}
					});
			}
			
			this.listener = getListener();
			displayer.addEventListener(Event.ENTER_FRAME, listener);
		}
		
		public function kill() {
			cleanBox();
			displayer.removeEventListener(Event.ENTER_FRAME, listener);
			for(var i:int = 0; i < bubbles.length; i++)
				displayer.removeChild(bubbles[i]);
		}
		
		protected function cleanBox() {
			if(displayer.contains(loc_mc))
				displayer.removeChild(loc_mc);
		}
		
		protected function getListener():Function {
			function listener(event:Event):void {
				if(flow)
					return;
				
				motionTracker.track();
				for(var i:int = 0; i < bubbles.length; i++) {
					var b:BubbleMovieClip = bubbles[i];
					if(!b.isMini() && b != currentBubble)
						b.down();
				}
				if(!motionTracker.hasMovement) {
					if(currentBubble != null) {
						currentBubble.up();
						//currentBubble.up();
					}
					
					return;
				}
					
				loc_mc.x = motionTracker.motionArea.x;
				loc_mc.y = motionTracker.motionArea.y;
				
				var bub:BubbleMovieClip = intersection();				
				if(bub == null)
					currentBubble = null;
				else if(currentBubble == bub)
					currentBubble.up();
				else
					currentBubble = bub;
				
			}
		
			return listener;
		}
		
		private function intersection():BubbleMovieClip {
			var centerX:Number = loc_mc.x + loc_mc.width / 2;
			var centerY:Number = loc_mc.y + loc_mc.height / 2;
			var smallestSoFar:Number = 100;
			var smallestBubble:BubbleMovieClip = null;
			for(var i:int = 0; i < bubbles.length; i++)  {
				var len:Number = Math.sqrt(Math.pow(bubbles[i].x - centerX, 2) + 
					Math.pow(bubbles[i].y - centerY, 2));
				if(len <= smallestSoFar) {
					smallestSoFar = len;
					smallestBubble = bubbles[i];
				}
			}
			
			return smallestBubble;
		}
	}
}